from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic_settings import BaseSettings
import os
import asyncpg
import motor.motor_asyncio
import redis.asyncio as redis
from typing import Optional

class Settings(BaseSettings):
    app_name: str = "AI Writing Platform API"
    api_version: str = "v1"
    debug: bool = True
    
    # Database
    database_url: str = os.getenv("DATABASE_URL", "postgresql://admin:newhand@localhost:15432/aipaper_db")
    mongodb_url: str = os.getenv("MONGODB_URL", "mongodb://admin:newhand@localhost:27017/ai_writing?authSource=admin")
    redis_url: str = os.getenv("REDIS_URL", "redis://localhost:6379")
    
    # CORS
    cors_origins: list[str] = ["http://localhost:3000", "http://localhost:5173", "http://localhost:3001"]
    
    # Security
    jwt_secret: str = os.getenv("JWT_SECRET", "your-secret-key-here")
    jwt_algorithm: str = "HS256"
    jwt_expiration_minutes: int = 60 * 24  # 24 hours

    class Config:
        env_file = ".env"

settings = Settings()

# Global connections
postgres_pool: Optional[asyncpg.Pool] = None
mongodb_client: Optional[motor.motor_asyncio.AsyncIOMotorClient] = None
redis_client: Optional[redis.Redis] = None

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    global postgres_pool, mongodb_client, redis_client
    
    try:
        # Initialize PostgreSQL connection pool
        postgres_pool = await asyncpg.create_pool(
            settings.database_url,
            min_size=10,
            max_size=20,
            command_timeout=60
        )
        print("✅ PostgreSQL connected")
    except Exception as e:
        print(f"❌ PostgreSQL connection failed: {e}")
    
    try:
        # Initialize MongoDB client
        mongodb_client = motor.motor_asyncio.AsyncIOMotorClient(settings.mongodb_url)
        await mongodb_client.server_info()
        print("✅ MongoDB connected")
    except Exception as e:
        print(f"❌ MongoDB connection failed: {e}")
    
    try:
        # Initialize Redis client
        redis_client = redis.from_url(settings.redis_url, decode_responses=True)
        await redis_client.ping()
        print("✅ Redis connected")
    except Exception as e:
        print(f"❌ Redis connection failed: {e}")
    
    yield
    
    # Shutdown
    if postgres_pool:
        await postgres_pool.close()
    if mongodb_client:
        mongodb_client.close()
    if redis_client:
        await redis_client.close()

# Create FastAPI app
app = FastAPI(
    title=settings.app_name,
    version=settings.api_version,
    lifespan=lifespan
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Health check endpoint
@app.get("/health")
async def health_check():
    status = {
        "status": "healthy",
        "service": settings.app_name,
        "version": settings.api_version,
        "databases": {
            "postgresql": "unknown",
            "mongodb": "unknown",
            "redis": "unknown"
        }
    }
    
    # Check PostgreSQL
    if postgres_pool:
        try:
            async with postgres_pool.acquire() as conn:
                await conn.fetchval("SELECT 1")
                status["databases"]["postgresql"] = "connected"
        except:
            status["databases"]["postgresql"] = "disconnected"
    
    # Check MongoDB
    if mongodb_client:
        try:
            await mongodb_client.server_info()
            status["databases"]["mongodb"] = "connected"
        except:
            status["databases"]["mongodb"] = "disconnected"
    
    # Check Redis
    if redis_client:
        try:
            await redis_client.ping()
            status["databases"]["redis"] = "connected"
        except:
            status["databases"]["redis"] = "disconnected"
    
    return status

# Root endpoint
@app.get("/")
async def root():
    return {
        "message": "Welcome to AI Writing Platform API",
        "version": settings.api_version,
        "docs": "/docs"
    }

# API v1 routes
from src.routes import ai_hints
app.include_router(ai_hints.router, prefix="/api/v1/ai", tags=["ai"])